/*
 * @Description: 条目检测 - 可用性检测
 * @Author: Rfan
 * @Date: 2022-10-10 14:19:09
 * @LastEditTime: 2022-10-22 17:23:12
 */

import { forwardRef, Ref, useEffect, useImperativeHandle, useState } from 'react';
import { Checkbox, Space } from 'antd';
import cs from 'classnames';
import classnames from 'classnames/bind';
import { isNullObj } from '@/utils';
import { useAddPlanDialogContext } from '../../../contexts/AddPlanDialogContext';
import { CheckProps, EnumUsabilityRuleType } from '../../../../../../dictionaries';
import type { IPropsRule } from '../../../../../../interface';
import styles from '../../../styles/entryPanes.module.scss';
import mainStyles from '../../../styles/main.module.scss';

const cx = classnames.bind(styles);
const mainCx = classnames.bind(mainStyles);

// CD可用性规则列表类型
type TRuleList = IPropsRule<EnumUsabilityRuleType>[];
// 条目可用性完整类型
export interface IUsabilityFullRules {
  ruleType: CheckProps.Usability;
  rules: IPropsRule<EnumUsabilityRuleType>[];
}

const EntryUsabilityCheck = forwardRef((props: any, ref: Ref<unknown>) => {
  const { currentRuleInfo, getPropertyRules, getRuleState, setRuleState } =
    useAddPlanDialogContext();

  // 规则列表
  const [ruleList, setRuleList] = useState<TRuleList>([]);

  useImperativeHandle(ref, () => ({
    save: () => {
      const fullRules: IUsabilityFullRules = {
        ruleType: CheckProps.Usability,
        rules: ruleList
      };
      return fullRules;
    }
  }));

  /**
   * @description: 获取到规则后回写
   */
  useEffect(() => {
    if (currentRuleInfo && !isNullObj(currentRuleInfo)) {
      const ruleObj = getPropertyRules(CheckProps.Usability);
      setRuleList(ruleObj?.rules || []);
    }
  }, [currentRuleInfo]);

  return (
    <div className={cs(mainCx('property-wrap'), cx('property-usability'))}>
      <Space className={mainCx('property--title-wrap')}>
        <h6 className={mainCx('property--title')}>元数据检测</h6>
      </Space>
      <div>
        <Checkbox
          checked={getRuleState(EnumUsabilityRuleType.ItemTargetAccessible, ruleList)}
          onChange={(evt) => {
            setRuleState(
              evt.target.checked,
              EnumUsabilityRuleType.ItemTargetAccessible,
              ruleList,
              setRuleList
            );
          }}
        >
          目标数据库中的元数据可访问性检测
        </Checkbox>
      </div>
    </div>
  );
});

export default EntryUsabilityCheck;
